package cybertechcebu.task
{
	import cybertechcebu.FTPClient;
	import cybertechcebu.FTPCommand;
	import cybertechcebu.FTPResponse;
	import cybertechcebu.enum.Commands;
	import cybertechcebu.enum.Responses;
	
	import mx.controls.Alert;
	import mx.core.mx_internal;
	import mx.utils.object_proxy;

	public class ChangeDirTask extends Task
	{
		private var directory:String;

		public function ChangeDirTask(client:FTPClient, directory:String)
		{
			super(client);
			this.directory = directory;
		}

		override protected function startTask():void
		{
			sendCommand(new FTPCommand(Commands.CWD, directory));
		}

		override public function handleResponse(response:FTPResponse):void
		{
			switch (response.code)
			{
				case Responses.FILE_ACTION_OK:
					sendCommand(new FTPCommand(Commands.PWD));
					break;
				case Responses.PATHNAME_CREATED:
					client.currentDirectory = parseCurrentDir(response.str);
					dispatchTaskEnd(true);
					break;
				default:
					dispatchTaskError("Unhandled response code: " + response.code);
			}
		}

		private function parseCurrentDir(currentDirResponse:String):String
		{
			var match:Array = currentDirResponse.match(/".+"/g);
			if (match == null)
				throw new Error("Error parsing current dir!");
			return match[0].replace(/"/g, "");
		}
	}
}
